from typing import Annotated
from fastapi import Depends
from forward.api.h5.orm.lucky.code import CodeORM
from forward.common.enums import CodeStatusEnum
from forward.exceptions.base import AppException
from forward.extend.pydantic.result_api import ResultAPI
from forward.http_base import HttpResp


class CodeService:
    def __init__(self, code_orm: Annotated[CodeORM, Depends()]) -> None:
        self.code_orm = code_orm

    async def detail(self, code_: str):
        code = await self.code_orm.get_one_by_filters(code=code_)
        if not code:
            raise AppException(exc=HttpResp.FAILED, msg="码不存在")
        if not code.activity_id:
            raise AppException(exc=HttpResp.FAILED, msg="活动不存在")
        return ResultAPI(data=code)

    async def chang_status(self, id, status: CodeStatusEnum):
        record = await self.code_orm.update(id, {"status": status.value})
        return record

    async def check_code_status(self, code_: str):
        code = await self.code_orm.get_one_by_filters(code=code_)
        if not code:
            raise AppException(exc=HttpResp.FAILED, msg="码不存在")
        if code.status == CodeStatusEnum.USED.value:
            raise AppException(exc=HttpResp.FAILED, msg="码已使用")

        return ResultAPI(data=code)
